package com.gaoqi.springboot_shiro.Inteceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaoqi.springboot_shiro.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 自定JWT 拦截器
 */
public class JWTInteceptor implements HandlerInterceptor {
    private static String exInfo = "no exception";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求头中获取token 信息
        String token = request.getHeader("token");
        System.out.println("================GetToken开始拦截================");
        try {
            //验证签名 token  存在空指针异常**************
            JWTUtils.testSign(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            exInfo = "******************无效签名";
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            exInfo = "******************签名过期";
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            exInfo = "******************算法不一致";
        } catch (Exception e) {
            e.printStackTrace();
            exInfo = "******************无效令牌";
        }

        System.out.println("======================" + exInfo + "=========================");

        HashMap<String, Object> map = new HashMap<String, Object>();

        //返回前端异常信息
        map.put("state", false);
        map.put("info", exInfo);

        //将异常信息 转换为json 格式字符
        String json = new ObjectMapper().writeValueAsString(map);
        //设置编码格式
        response.setContentType("application/json;charset=utf-8");

        //响应前端
        response.getWriter().write(json);
        return false;
    }
}
